package com.macro.mall.portal.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.model.UmsMember;
import com.macro.mall.model.UmsUser;
import com.macro.mall.portal.service.UmsMemberService;
import com.macro.mall.portal.service.UmsUserService;
import com.macro.mall.portal.util.WechatUtil;
import com.macro.mall.security.util.JwtTokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

/**
 * 会员登录注册管理Controller
 * Created by macro on 2018/8/3.
 */
@Controller
@Api(tags = "UmsMemberController", description = "会员登录注册管理")
@RequestMapping("/sso")
public class UmsMemberController {
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private UmsMemberService memberService;

    @Autowired
    private UmsUserService umsUserService;

    @ApiOperation("会员注册")
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult register(@RequestParam String username,
                                 @RequestParam String password,
                                 @RequestParam String telephone,
                                 @RequestParam String authCode) {
        memberService.register(username, password, telephone, authCode);
        return CommonResult.success(null,"注册成功");
    }

    @ApiOperation("会员登录")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult login(@RequestParam String username,
                              @RequestParam String password) {
        String token = memberService.login(username, password);
        if (token == null) {
            return CommonResult.validateFailed("用户名或密码错误");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
    }

    @ApiOperation("会员微信登录")
    @RequestMapping(value = "/wxlogin", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult wxlogin(@RequestBody JSONObject jsonObject) {
        String rawData=jsonObject.get("rawData").toString();

        String signature=jsonObject.get("signature").toString();
        String encryptedData=jsonObject.get("encryptedData").toString();
        String iv=jsonObject.get("iv").toString();
        String code=jsonObject.get("code").toString();


        // 1.接收小程序发送的code
        // 2.开发者服务器 登录凭证校验接口 appi + appsecret + code
        JSONObject SessionKeyOpenId = WechatUtil.getSessionKeyOrOpenId(code);
        // 3.接收微信接口服务 获取返回的参数
        String openid = SessionKeyOpenId.getString("openid");
        String sessionKey = SessionKeyOpenId.getString("session_key");
        String unionid = SessionKeyOpenId.getString("unionid");
        // 4.校验签名 小程序发送的签名signature与服务器端生成的签名signature2 = sha1(rawData + sessionKey)
        String signature2 = DigestUtils.sha1Hex(rawData + sessionKey);
        if (!signature.equals(signature2)) {
            return CommonResult.failed("签名校验失败");
        }
        // 用户非敏感信息：rawData
        // 签名：signature
        JSONObject rawDataJson = JSON.parseObject(rawData);

        // 5.根据返回的User实体类，判断用户是否是新用户，是的话，将用户信息存到数据库；不是的话，更新最新登录时间
        UmsUser user= umsUserService.findUserByopenid(openid);
        String userId="";
        String password=openid.substring(openid.length()-6);
        Integer id=0;
        if(user==null){
            userId=UUID.randomUUID().toString();
            //添加用户信息到数据库
            UmsMember umsMember=new UmsMember();
            umsMember.setUsername(openid);
            umsMember.setPassword(password);
            umsMember.setNickname(rawDataJson.getString("nickName"));
            umsMember.setGender(rawDataJson.getInteger("gender"));
            umsMember.setIcon(rawDataJson.getString("avatarUrl"));
            umsMember.setCity(rawDataJson.getString("city"));
            String memberId=UUID.randomUUID().toString();
            umsMember.setMemberid(memberId);
            memberService.addwxMember(umsMember);
            UmsUser umsUser=new UmsUser();
            umsUser.setOpenid(openid);
            umsUser.setUserid(userId);
            umsUser.setMemberid(memberId);
            umsUser.setUnnionid(unionid);
            umsUser.setType(1);
            umsUser.setStatus(1);
            umsUser.setCreatetime(DateTime.now().toString());
            umsUserService.addUser(umsUser);
            id=umsUser.getId();
        }else {
            userId=user.getUserid();
            id=user.getId();
        }
        //User user = this.userMapper.selectById(openid);
        // uuid生成唯一key，用于维护微信小程序用户与服务端的会话
        //String skey = UUID.randomUUID().toString();

        String token = memberService.login(openid, password);
        if (token == null) {
            return CommonResult.validateFailed("用户名或密码错误");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        tokenMap.put("userId",userId);
        tokenMap.put("uId",id.toString());
        return CommonResult.success(tokenMap);
    }



    @ApiOperation("获取会员信息")
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult info(Principal principal) {
        if(principal==null){
            return CommonResult.unauthorized(null);
        }
        UmsMember member = memberService.getCurrentMember();
        return CommonResult.success(member);
    }

    @ApiOperation("获取验证码")
    @RequestMapping(value = "/getAuthCode", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult getAuthCode(@RequestParam String telephone) {
        String authCode = memberService.generateAuthCode(telephone);
        return CommonResult.success(authCode,"获取验证码成功");
    }

    @ApiOperation("修改密码")
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updatePassword(@RequestParam String telephone,
                                 @RequestParam String password,
                                 @RequestParam String authCode) {
        memberService.updatePassword(telephone,password,authCode);
        return CommonResult.success(null,"密码修改成功");
    }


    @ApiOperation(value = "刷新token")
    @RequestMapping(value = "/refreshToken", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult refreshToken(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        String refreshToken = memberService.refreshToken(token);
        if (refreshToken == null) {
            return CommonResult.failed("token已经过期！");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", refreshToken);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
    }

    @ApiOperation(value = "验证token")
    @RequestMapping(value = "/validateToken", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult validateToken(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        JwtTokenUtil jwtTokenUtil=new JwtTokenUtil();
        return CommonResult.success("");
    }
}
